// https://www.lintcode.com/problem/subtree-of-another-tree/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param s: the s' root
     * @param t: the t' root
     * @return: whether tree t has exactly the same structure and node values with a subtree of s
     */
    public boolean isSubtree(TreeNode s, TreeNode t) {
        // Write your code here
        if ((s == null) && (t != null)) {
            return false;
        }
        if (isSameTree(s, t)) {
            return true;
        } else {
            return isSubtree(s.left, t) || isSubtree(s.right, t);
        }
    }
    
    protected boolean isSameTree(TreeNode s, TreeNode t) {
        if ((s != null) && (t != null)) {
            if (s.val != t.val) {
                return false;
            }        
        } else if ((s == null) && (t == null)) {
            return true;
        } else {
            return false;
        }
        return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
    }
}